import {memo, useState} from 'react';

import {Button, message, Upload} from 'antd';
import {updateMyUserUsingPost} from "@/services/backend/userController";
import {getInitialState} from "@/app";
import {useModel} from "@@/exports";

interface UploadAvatarTestProps {
  userInfo?: API.UserVO | undefined,
  onRefresh?: () => void
}

const index = memo(({userInfo, onRefresh}: UploadAvatarTestProps) => {

  const { setInitialState} = useModel('@@initialState');
  const [loading, setLoading] = useState(false);

  // 更新登录用户状态
  const setLoginUserInfo = async () => {
    const newUserInfo = await getInitialState();
    setInitialState(newUserInfo);
  }


  const beforeUpload = (file: any) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('只能上传 JPG/PNG 文件!');
    }
    const isLt1M = file.size / 1024 / 1024 < 10;
    if (!isLt1M) {
      message.error('图片不能超过10MB!');
    }
    return isJpgOrPng && isLt1M;
  };

  const handleChange = async (info: any) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      if (info.file.response.code === 0) {
        setLoading(false);
        const updatedUserInfo = {
          ...userInfo,
          userAvatar: info.file.response.data
        };
        const res = await updateMyUserUsingPost(updatedUserInfo);
        setLoading(false)
        if (res.code === 0) {
          setLoading(false)
          onRefresh?.();
          await setLoginUserInfo();
          message.success("头像修改成功")
        } else {
          // message.error("头像修改失败-" + res.message)
          setLoading(false)
        }
      }
    }
  };


  return (
    <Upload
      // listType="picture-card"
      className="avatar-uploader"
      showUploadList={false}
      action="http://localhost:8101/api/file/upload"
      // action="http://49.235.171.59:8101/api/file/upload"
      beforeUpload={beforeUpload}
      onChange={handleChange}
      name='file'
      data={{biz: 'user_avatar'}}
    >
      <div style={{marginTop: "10px"}}>
        <Button loading={loading}>修改头像</Button>
      </div>
    </Upload>
  )
})

export default index
